package com.luo.demo.dynamic.tenant.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.luo.demo.dynamic.tenant.dto.MyDataQueryDto;
import com.luo.demo.dynamic.tenant.entity.MyData;
import com.luo.demo.dynamic.tenant.mapper.MyDataMapper;
import com.luo.demo.dynamic.tenant.service.IMyDataService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * <p>
 * 我的数据 服务实现类
 * </p>
 *
 * @author luohq
 * @since 2022-08-07
 */
@Service
public class MyDataServiceImpl extends ServiceImpl<MyDataMapper, MyData> implements IMyDataService {

    @Resource
    private MyDataMapper myDataMapper;

    @Override
    public MyData findById(Long id) {
        return this.myDataMapper.selectById(id);
    }


    @Override
    public MyData findByQuery(MyDataQueryDto myDataQueryDto) {
        return this.myDataMapper.selectOne(Wrappers.<MyData>lambdaQuery()
                .eq(Objects.nonNull(myDataQueryDto.getId()), MyData::getId, myDataQueryDto.getId())
                .like(StringUtils.hasText(myDataQueryDto.getMyName()), MyData::getMyName, myDataQueryDto.getMyName()));
    }

    @Override
    public MyData findByName(String myName) {
        //mapper.xml自定义查询 - 支持自动拼接租户Id参数
        return this.myDataMapper.selectByName(myName);
    }

    /**
     * 支持事务
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer addData(MyData myData) {
        //支持自动设置tenantId
        Integer retCount = this.myDataMapper.insert(myData);
        return retCount;
    }

    /**
     * 支持事务 - @DSTransactional区别于Spring @Transactional
     */
    @Override
    @DSTransactional
    @DS("ds1")
    public Integer addData1(MyData myData) {
        //支持自动设置tenantId
        Integer retCount = this.myDataMapper.insert(myData);
        return retCount;
    }
    /**
     * 支持事务 - @DSTransactional区别于Spring @Transactional
     */
    @DS("ds2")
    @Override
    @DSTransactional
    public Integer addData2(MyData myData) {
        //支持自动设置tenantId
        Integer retCount = this.myDataMapper.insert(myData);
        return retCount;
    }
}
